package tcp_client

import (
	"ServerDemo/config"
	"ServerDemo/protocal/protobuf"
	"fmt"
	"google.golang.org/protobuf/proto"
	"log"
	"net"
	"reflect"
	"time"
)

//测试 client
func TcpClient(port int) {

	time.Sleep(time.Second * 3)

	conn, err := net.Dial("tcp", fmt.Sprintf("localhost:%d", port))
	//_, err := net.Dial("tcp", fmt.Sprintf("localhost:%d", port))

	if err != nil {
		log.Printf("tcpFHTestClient, Dail error:%v\n", err)
	}

	protocal := protobuf.NewProtobufProtocal()

	go getData(protocal, conn)

	for i := 1; i <= 1; i++ {
		data := &protobuf.TestRequest{
			Name:   "czy",
			Age:    22,
			Items:  make([]string, 2),
			Status: protobuf.Status_Unlock,
		}

		//返回encode 的数据， 然后发送
		encodedData, _ := protocal.Encode(config.ACTION_PING, data)
		fmt.Println("发送数据：", data)
		_, err2 := conn.Write(encodedData)
		if err2 != nil {
			return
		}

		time.Sleep(time.Second * 1)
	}
}

func getData(protocal *protobuf.ProtobufProtocal, conn net.Conn) {

	for {
		response, err := protocal.ClientDecode(conn)
		if err != nil {
			continue
		}

		if reflect.ValueOf(response).IsNil() {
			continue
		}
		data := &protobuf.TestRequest{}
		err = proto.Unmarshal(response.Data, data)
		if err != nil {
			return
		}
		fmt.Println("客户端收到返回数据", data)

	}
}
